<template>
  <div style="height: 100%">
    <highcharts v-if="hcharOptions.series[0]" style="height:100%" :options="hcharOptions" ref="canvas">
    </highcharts>
    <div v-else :style="{'background-image':'url('+svgPath+')'}" class="empty"></div>
  </div>
</template>
<script>
import * as hchar from './types/index'
import Vue from 'vue'
import VueHighcharts from 'vue-highcharts'
import Highcharts from 'highcharts/highcharts'
import HighchartsMore from 'highcharts/highcharts-more'
import trans from 'assets/js/trans'
import Heatmap from 'highcharts/modules/heatmap'
import Treemap from 'highcharts/modules/treemap'
import HighchartsSolidGauge from 'highcharts/modules/solid-gauge'
HighchartsMore(Highcharts)
Heatmap(Highcharts)
Treemap(Highcharts)
HighchartsSolidGauge(Highcharts)
Vue.use(VueHighcharts, {
  Highcharts,
})

// 高亮显示示例
// "series": [{
//         "name": "市场份额",
//         "data": [{y:45,color:"rgba(23, 28, 31, 0.56)"}, 26.8, 12.8, 8.5, 6.2, 0.7],
// 或
//     "plotOptions": {
//         "series": {
//             allowPointSelect:true
//         }
//     }

// 或
// "series": [{
//        "name": "市场份额",
//        "data": [{y:45,selected:true},
// 或
// "series": [{
//        "name": "市场份额",
//        "data": [{y:45,className:'active'},
//选择事件
//选择和取消https://api.hcharts.cn/highcharts#series<line>.data.events.select
//例子 https://code.hcharts.cn/highcharts/JtHmX0

// keys
// linkedto


Highcharts.setOptions({
  credits: {
    enabled: false
  },
  global: {
    useUTC: false
  },
  colors: ['#7CB5EF', '#FDB54C', '#FB725C', '#5AC995', '#7CCDF7', '#AFD574', '#6CD3BF', '#4EC7D5', '#9F97D1', '#F9B383']
});
export default {
  props: {
    typesFile: '', //对应他types文件夹下面js文件名
    datas: {}, //报表数据集
    // dataSource: {}, //报表项选中的数据表id+表头下标
    axis: {}, //报表项选中的数据轴id+表头下标
    value: {}, //报表项选中的数据轴id+表头下标
    w: { //传width会检测不到变化
      type: Number,
    },
    h: { //传height会检测不到变化
      type: Number,
    },
  },
  data() {
    return {}
  },
  computed: {
    chartOption: function() {
      //自定义图表类型直接用
      return isNaN(this.typesFile) ? this.typesFile : hchar['hchar' + this.typesFile.replace('.', '_')]
    },
    svgPath: function() {
      //自定义图表类型固定用第一个图表svg
      return isNaN(this.typesFile) ? require('./types/1.1.svg') : require('./types/' + this.typesFile + '.svg')
    },
    // dataSelect: function() {
    //   return this.dataSource.map((n) => n.index)
    // },
    //所选的数据序列
    dataSeries: function() {
      let series = {}


      //遍历表格
      this.datas.forEach((n) => {
        let table = trans.str2HotData(n.content)

        //遍历列
        for (let rows = 0; rows < table.length; rows++) {

          //遍历行
          for (let cols = 0; cols < table[rows].length; cols++) {
            let index = n.id + '.' + cols,
              value = table[rows][cols]

            //过滤非空
            if (value !== null && value.toString().length) {

              //数字还原类型
              if (!isNaN(value)) {
                value = Number(value)
              }

              if (!series[index]) {
                series[index] = []
              } else {
                series[index].push(value)
              }

            }
          }

        }

      })

      return series
    },
    //真实数据x轴
    xAxis: function() {
      let arr = []
      let indexs = _.map(this.axis, 'index')
      return [_.assign({
        categories: this.dataSeries[indexs[0]]
      }, this.chartOption.xAxis ? this.chartOption.xAxis[0] : {})]
    },
    //真实数据y轴
    series: function() {
      let arr = []
      for (let i = 0; i < this.value.length; i++) {
        let chartOption = this.chartOption.series[Math.min(this.chartOption.series.length - 1, i)] //series有定义则取定义的，没有则取i对应的最后一个
        arr.push(_.assign({
          name: this.value[i].name,

          //pie要返回[name:,y:],其他图表返回值
          data: this.dataSeries[this.value[i].index].map((n, index) => {
            if (this.isPie) {
              //有传轴用轴名
              if (this.xAxis && this.xAxis[0] && this.xAxis[0].categories && this.xAxis[0].categories.length >= index) {
                return [this.xAxis[0].categories[index], n]
              }
              // 没有则为默认的slice
              else {
                return n
              }
            } else if (this.isTree) {
              if (this.xAxis && this.xAxis[0] && this.xAxis[0].categories && this.xAxis[0].categories.length >= index) {
                return {
                  name: this.xAxis[0].categories[index],
                  value: n,
                  colorValue: index + 1
                }
              }
              // 没有则为默认的slice
              else {
                return {
                  name: '',
                  value: n,
                  colorValue: index + 1
                }
              }
            } else if (this.isBubble) {

            } else {
              return n
            }
          })
        }, chartOption))
      }
      return arr
    },
    hcharOptions: function() {
      let canvas = this.canvas
      let options = Highcharts.merge({
          // chart: {
          //   renderTo: canvas,
          // },
          title: {
            text: ''
          },
          yAxis: {
            title: ''
          },
        }, this.chartOption, {
          series: this.series
        }, this.xAxis && this.xAxis[0] && this.xAxis[0].categories ? {
          xAxis: this.xAxis
        } : {})
        // if (!(this.options.series && this.options.series[0] && this.options.series[0].type)) {
        //   //图表类型切换时还原type
        //   for (let i = 0; i < options.series.length; i++) {
        //     delete options.series[i].type
        //   }
        // }
      window.console && console.log(options);
      // window.console && console.log(JSON.stringify(options));
      return options
    },
    isPie: function() {
      //用于判断series是否要返回[name:,y:]
      return this.typesFile == 3.3 || this.typesFile == 3.4
    },
    isTree: function() {
      //用于判断series是否要返回{name: 'A',value: 6,colorValue: 1}
      return this.typesFile == 3.5
    },
    //暂不支持散点图，因为要单独定义x,y,z轴
    isBubble: function() {
      //用于判断series是否要返回{
      //     name:'数据列 1',
      //     // 每个气泡包含三个值，x，y，z；其中 x，y用于定位，z 用于计算气泡大小
      //     data: [[97, 36, 79], [94, 74, 60], [68, 76, 58], [64, 87, 56], [68, 27, 73], [74, 99, 42], [7, 93, 87], [51, 69, 40], [38, 23, 33], [57, 86, 31]]
      // }
      return this.typesFile == 3.2
    },
  },
  methods: {},
  mounted() {
    window.console && console.log('mounted');
    // try {
    //   if (this.hcharOptions.series.length) {
    //     this.chart = Highcharts.chart(this.hcharOptions)
    //   } else {
    //     this.chart && this.chart.destroy()
    //     this.chart = ''
    //   }
    // } catch (err) {
    //   window.console && console.log('err', err);
    // }
  },
  updated() {
    window.console && console.log('updated');
  },
  created() {
    window.console && console.log('created', this.chart);
  },
  components: {},
  watch: {
    options: function(val) {
      window.console && console.log(val);
    },
    hcharOptions: function(val) {
      window.console && console.log(33, val);
      // if (this.$refs.canvas) {
      //   // try {
      //   if (val.series.length) {
      //     this.chart = Highcharts.chart(val)
      //   } else {
      //     this.chart && this.chart.destroy()
      //     this.chart = ''
      //       //清空图表内容后视图没有调用slot=empty
      //   }
      //   // } catch (err) {}
      // }
    },
    value: function(val) {
      window.console && console.log('value changed');
    },
    w: function(val) {
      window.console && console.log('width changed');
      try {
        let canvas = this.$refs.canvas
        if (canvas && canvas.chart) {
          canvas.chart.reflow()
        }
      } catch (err) {}
    },
    h: function(val) {
      window.console && console.log('height changed');
      try {
        let canvas = this.$refs.canvas
        if (canvas && canvas.chart) {
          canvas.chart.reflow()
        }
      } catch (err) {}
    },
  },
}
</script>
<style lang="less" scope>
.empty {
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
</style>
